var power = localStorage.getItem("identity");
layui.use(['form','layer','laydate','table','laytpl','layedit'],function(){
    var form = layui.form,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        layedit = layui.layedit,                                                     
        table = layui.table;
  
    var col = {
        "student" : [
            {field: 'newsName', title: '文章标题', width:350},
            //{field: 'picture',title: '缩略图',align: 'center',width: 170,templet: '#thumbnailImages'}, 
            {field: 'newsTime', title: '发布时间', align:'center', minWidth:110, templet:function(d){
                return d.newsTime.substring(0,10);
            }},
            {title: '操作', width:70, templet:'#newsListBar',fixed:"right",align:"center"}
        ],
        "other" : [
            {type: "checkbox", fixed:"left", width:50},
            {field: 'newsId', title: 'ID', width:60, align:"center" ,fixed:"left"},
            {field: 'newsName', title: '文章标题', width:350},
            //{field: 'picture',title: '缩略图',align: 'center',width: 170,templet: '#thumbnailImages'}, 
            // {field: 'newsStatus', title: '发布状态',  align:'center',templet:"#newsStatus"},
            // {field: 'newsLook', title: '浏览权限', align:'center'},
            {field: 'newsTop', title: '是否置顶', align:'center', templet:function(d){
                return '<input type="checkbox" name="newsTop" lay-filter="newsTop" lay-skin="switch" lay-text="是|否" '+d.newsTop+'>'
            }},
            {field: 'newsTime', title: '发布时间', align:'center', minWidth:110, templet:function(d){
                return d.newsTime.substring(0,10);
            }},
            {title: '操作', width:130, templet:'#newsListBar',fixed:"right",align:"center"}
        ],
    }
    if( power == 'student' || power == 'teacher' ){
        col = col.student;
    }else{
        col = col.other;
        $("#add_del_btn").append('<div class="layui-inline"><a class="layui-btn  addNews_btn">添加文章</a></div> ');
        $("#add_del_btn").append('<div class="layui-inline"><a class="layui-btn  delAll_btn">批量删除</a></div>');
    }
    //新闻列表

    var tableIns = table.render({
		  elem: '#newsList',
		  url : 'http://127.0.0.1:8000/newslist',
		  cellMinWidth : 95,
		  page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
            layout: ['prev', 'page', 'next', 'skip', 'limit', 'count'] //自定义分页布局
            //,curr: 5 //设定初始在第 5 页
            , limit: 10//一页显示多少条
            , limits: [10, 15, 20, 25]//每页条数的选择项
            
            , groups: 5//只显示 2 个连续页码
            // ,first: "首页" //不显示首页
            // ,last: "尾页" //不显示尾页
        },
        //toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
        defaultToolbar: ['filter', 'exports', 'print'],
        //limit : 20,
        //limits : [10,15,20,25],
		  id : "newsListTable",
        cols : [
            col
        ],
		done: function(res, curr, count) {
			//图片放大预览
			var ids;
			for (var j in res.data) {
				ids = res.data[j].newsId;
				layer.photos({
					photos: '.thumbnailImages'+ids 
				});
			}
			
		}
    });

    //是否置顶
    form.on('switch(newsTop)', function(data){
        var index = layer.msg('修改中，请稍候',{icon: 16,time:false,shade:0.8});
        setTimeout(function(){
            layer.close(index);
            if(data.elem.checked){
                layer.msg("置顶成功！");
            }else{
                layer.msg("取消置顶成功！");
            }
        },500);
    })

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click",function(){
        if($(".searchVal").val() != ''){
            table.reload("newsListTable",{
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    key: $(".searchVal").val()  //搜索的关键字
                }
            })
            layer.msg("搜索结果如下");
        }else{
            location.reload();
         layer.msg("请输入搜索的内容");
        }
    });

    //添加文章
    function addNews(edit){
        var index = layui.layer.open({
            title : edit?"修改文章" :"添加文章",
            type : 2,
			area: ['90%', '90%'],
			fixed: false, //不固定
			maxmin: true,
            content : "newsAdd.html",
            success : function(layero, index){
                var body = layui.layer.getChildFrame('body', index);
                if(edit){
                    body.find(".newsName").val(edit.newsName);
                    body.find(".abstract").val(edit.abstract);
                    body.find(".thumbImg").attr("src",edit.newsImg);
                    body.find("#news_content").val(edit.content);
                    // body.find(".newsStatus select").val(edit.newsStatus);
                    // body.find(".openness input[name='openness'][title='"+edit.newsLook+"']").prop("checked","checked");
                    // body.find(".newsTop input[name='newsTop']").prop("checked",edit.newsTop);
                    editIndex = layedit.build(body.find("#news_content"), {
                        height: 535,
                        tool: [
                            'strong','italic','underline','del','|','left','center','right' ,'|','image' 
                        ]
                    });  
                   
                    var iframeWindow = layero.find('iframe')[0].contentWindow;
                    //重新渲染
                    iframeWindow.layui.form.render();
                } 
                setTimeout(function(){
                    layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        })
       
    }
    //学生文章详情
    function detailNews(edit){
        var index = layui.layer.open({
            title : "查看文章",
            type : 2,
			area: ['90%', '90%'],
			fixed: false, //不固定
			maxmin: true,
            content : "detailNews.html",
            success : function(layero, index){
                var body = layui.layer.getChildFrame('body', index);
                if(edit){
                    body.find(".newsName").val(edit.newsName);
                    body.find(".abstract").val(edit.abstract);
                    body.find(".thumbImg").attr("src",edit.newsImg);
                    body.find("#news_content").val(edit.content);
                    // body.find(".newsStatus select").val(edit.newsStatus);
                    // body.find(".openness input[name='openness'][title='"+edit.newsLook+"']").prop("checked","checked");
                    // body.find(".newsTop input[name='newsTop']").prop("checked",edit.newsTop);
                    var editIndex = layedit.build(body.find("#news_content"), {
                        height: 535,
                        tool: [
                            'fontSize'
                        ]
                    }); //获取新窗口对象
                    var iframeWindow = layero.find('iframe')[0].contentWindow;
                    //重新渲染
                    iframeWindow.layui.form.render();
                }
                setTimeout(function(){
                    layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        })
       
    }
    $(".addNews_btn").click(function(){
        addNews();
    })

    //批量删除
    $(".delAll_btn").click(function(){
        var checkStatus = table.checkStatus('newsListTable'),
            data = checkStatus.data,
            newsId = [];
        if(data.length > 0) {
            for (var i in data) {
                newsId.push(data[i].newsId);
            }
            layer.confirm('确定删除选中的文章？', {icon: 3, title: '提示信息'}, function (index) {
                $.get("http://127.0.0.1:8000/newsalldel",{
                    newsId : newsId  //将需要删除的newsId作为参数传入
                },function(data){
                tableIns.reload();
                layer.close(index);
                })
            })
        }else{
            layer.msg("请选择需要删除的文章");
        }
    })

    //列表操作
    table.on('tool(newsList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
			console.log(obj)
        if(layEvent === 'edit'){ //编辑
            addNews(data);
        } else if(layEvent === 'detail'){
            detailNews(data);
        }else if(layEvent === 'del'){ //删除
            layer.confirm('确定删除此文章？',{icon:3, title:'提示信息'},function(index){
                $.get("http://127.0.0.1:8000/newsdel",{
                    newsId : data.newsId  //将需要删除的newsId作为参数传入
                },function(data){
                    tableIns.reload();
                    layer.close(index);
                })
            });
        } 
    });

})